package com.example.diaoxinlei

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.diaoxinlei.ui.theme.Student
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.ObjectInputStream
import java.io.ObjectOutputStream

class MainActivity : AppCompatActivity() {

    private lateinit var recyclerView: RecyclerView
    private lateinit var addButton: Button
    private lateinit var studentAdapter: StudentAdapter
    private val students = mutableListOf<Student>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        title = "刁鑫磊2022110507"

        recyclerView = findViewById(R.id.recycler_view_students)
        addButton = findViewById(R.id.btn_add_student)

        studentAdapter = StudentAdapter(students)
        recyclerView.adapter = studentAdapter
        recyclerView.layoutManager = LinearLayoutManager(this)

        loadStudents()

        addButton.setOnClickListener {
            startActivityForResult(Intent(this, SecondActivity::class.java), 1)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1 && resultCode == RESULT_OK) {
            data?.getSerializableExtra("student")?.let { student ->
                students.add(student as Student)
                studentAdapter.notifyDataSetChanged()
                saveStudents()
            }
        }
    }

    private fun saveStudents() {
        val fileOut = ObjectOutputStream(FileOutputStream(getFilesDir().absolutePath + "/students.dat"))
        fileOut.writeObject(students)
        fileOut.close()
    }

    private fun loadStudents() {
        val file = File(getFilesDir(), "students.dat")
        if (file.exists()) {
            val fileIn = ObjectInputStream(FileInputStream(file))
            students.clear()
            students.addAll(fileIn.readObject() as List<Student>)
            fileIn.close()
            studentAdapter.notifyDataSetChanged()
        }
    }
}